/*
 * @Author: qianduanxuyaochendian lxy_01@outlook.com
 * @Date: 2022-05-19 16:35:29
 * @LastEditors: qianduanxuyaochendian lxy_01@outlook.com
 * @LastEditTime: 2022-05-24 22:32:04
 * @FilePath: \job\server\router\companyRouter.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 引入expres
const express = require("express")
// 引入路由模块
const router = express.Router()
// 引入数据库
const connection = require("../db/sql.js")
// 引入时间处理插件
const moment = require("moment")

// 引入图片上传工具
const upload = require("../utils/upload.js")

// 引入token验证模块
const { verifyToken } = require("../config/token.js")

const { ERROR_MSG } = require("../config/global")

//引入multer (nodejs中处理multipart/form-data数据格式(主要用在上传功能中）的中间件。该中间件不处理multipart/form-data数据格式以外的任何形式的数据)
const multer = require("multer")

// fieldname: 表单name名
// originalname: 上传的文件名
// encoding： 编码方式
// mimetype: 文件类型
// buffer: 文件本身
// size：尺寸
// destination: 保存路径
// filename： 保存后的文件名 不含后缀
// path： 保存磁盘路径+保存后的文件名 不含后缀

//引入fs  (nodejs中的文件系统模块)
const fs = require("fs")

// 获取学生个人简历信息
router.post("/getStudentInfo", (req, res) => {
  const userInfo = verifyToken(res, req.headers.authorization)
  let id = userInfo.id
  const sql = `select * from s_student where user_id = ${id}`
  connection.query(sql, (err, result) => {
    if (result) {
      res.reply_success(result)
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})



// 修改学生信息
router.post("/editStudentInfo", (req, res) => {
  // console.log(req.body);
  // const userInfo = verifyToken(res, req.headers.authorization)
  // let id = userInfo.id
  const sql = `UPDATE s_student SET age =?,phone=?,email=?,educational_experience=?,skill=?,project_experience=?,dream_position=?,dream_salary=?,self_evaluation=? WHERE id=?`
  connection.query(
    sql,
    [
      req.body.age,
      req.body.phone,
      req.body.email,
      req.body.educational_experience,
      req.body.skill,
      req.body.project_experience,
      req.body.dream_position,
      req.body.dream_salary,
      req.body.self_evaluation,
     req.body.id,
    ],
    (err, result) => {
      if (result) {
        res.reply_success(result)
      } else {
        res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "编辑失败")
      }
    }
  )
})

//获取学生用户信息
router.post("/getStudentPicture", (req, res) => {
  const uid = req.body.uid
  const sql = `select avatar from s_user where id =${uid}`
  connection.query(sql, (err, result) => {
    if (result) {
      res.reply_success(result)
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

//获取学生笔试/面试题数据
router.post("/getTopic", (req, res) => {
  const sql = `select id,company_name,topic from s_interview_questions`
  connection.query(sql, (err, result) => {
    if (result) {
      res.reply_success(result)
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

// 增加笔试/面试题
router.post("/addTopic", (req, res) => {
  const sql = `INSERT INTO s_interview_questions VALUES(?,?,?,?) `
  // const data = [
  //   parseInt(req.body.id),
  //   parseInt(req.body.student_id),
  //   `${req.body.company_name}`,
  //   `${req.body.topic}`,
  // ]
  // console.log(data)
  connection.query(
    sql,
    [
      parseInt(req.body.id),
      parseInt(req.body.student_id),
      `${req.body.company_name}`,
      `${req.body.topic}`,
    ],
    (err, result) => {
      if (result) {
        res.reply_success(result)
      } else {
        res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "插入失败")
      }
    }
  )
})

//更新面试题
router.post("/editTopic", (req, res) => {
  const sql = `UPDATE s_interview_questions SET company_name =?,topic =? WHERE id = ?`
  connection.query(
    sql,
    [`${req.body.company_name}`, `${req.body.topic}`, parseInt(req.body.id)],
    (err, result) => {
      if (result) {
        res.reply_success(result)
      } else {
        res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "编辑失败")
      }
    }
  )
})

//删除面试题
router.post("/deleteTopic", (req, res) => {
  const sql = `DELETE FROM s_interview_questions where id =?`
  connection.query(sql, parseInt(req.body.id), (err, result) => {
    if (result.affectedRows === 1) {
      res.reply_success(result)
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "删除失败")
    }
  })
})

// 新增学生简历
router.post("/addResume", (req, res) => {
  const sql =
    "INSERT INTO `s_student`(`id`, `user_id`, `name`, `age`, `educational_experience`, `skill`, `project_experience`, `dream_position`, `dream_salary`, `self_evaluation`,`email`,`phone`,`pages_id`) VALUES (?, ?, ?,?, ?, ?, ?, ?, ?, ?,?,?,?);"
  connection.query(
    sql,
    [
      ,
      req.body.user_id,
      req.body.name,
      parseInt(req.body.age),
      req.body.educational_experience,
      req.body.skill,
      req.body.project_experience,
      req.body.dream_position,
      req.body.dream_salary,
      req.body.self_evaluation,
      req.body.email,
      req.body.phone,
      req.body.pages_id,
    ],
    (err, result) => {
      if (result.affectedRows === 1) {
        res.reply_success({ status: 0, code: 200 })
      } else {
        res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "新增失败")
      }
    }
  )
})

//实现投递简历到相应公司
router.post("/sendResume", (req, res) => {
  const userInfo = verifyToken(res, req.headers.authorization)
  // console.log(userInfo.id);
  // console.log(req.body);
  const sql =
    "insert INTO `s_company_resume`(`id`,`user_id`,`company_id`,`apply_job`,`status`) VALUES(?,?,?,?,?)"
  connection.query(
    sql,
    [, userInfo.id, req.body.company_id, `${req.body.apply_job}`,0],
    (err, result) => {
      if (result.affectedRows === 1) {
        res.reply_success({ status: 0, code: 200 })
      } else {
        res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "新增失败")
      }
    }
  )
})

//获取当前登录用户所投递的简历列表
router.post("/getResumeList", (req, res) => {
  const userInfo = verifyToken(res, req.headers.authorization)
  const sql = `SELECT * FROM s_company_resume WHERE user_id = ${userInfo.id}`
  connection.query(sql, (err, result) => {
    if (result) {
      // console.log(result)
      // 关联所投递简历的公司名称
      let p = []
      for (let i = 0; i < result.length; i++) {
        const companyNameSql = `select name from s_company where id =${result[i]["company_id"]}`
        p.push(
          new Promise((resolve, reject) => {
            connection.query(companyNameSql, (err, results) => {
              if (results.length > 0) {
                result[i]["cname"] = results[0]["name"]
                resolve()
              }
            })
          })
        )
      }
      Promise.all(p).then((data) => {
        res.reply_success(result)
      })
    } else {
      res.reply_error(ERROR_MSG.UNAUTHORIZED_ACCESS, "查询失败")
    }
  })
})

module.exports = router
